package com.reebake.ideal.mybatis.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.reebake.ideal.mybatis.core.PageResultDeserializer;
import com.reebake.ideal.mybatis.core.PageResult;
import com.reebake.ideal.mybatis.core.PageResultSerializer;
import com.reebake.ideal.mybatis.properties.PaginationProperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
@Import({DataCommonFieldConfig.class, MybatisInterceptorConfig.class})
@EnableConfigurationProperties({PaginationProperties.class})
public class MybatisAutoConfiguration implements InitializingBean {
    @Autowired
    private PaginationProperties paginationProperties;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private Jackson2ObjectMapperBuilder builder;

    @Override
    public void afterPropertiesSet() throws Exception {
        SimpleModule simpleModule = new SimpleModule();
        // 自定义输出的属性名
        simpleModule.addSerializer(PageResult.class, new PageResultSerializer(paginationProperties));
        // 避免死循环，重新创建
        ObjectMapper mapper = builder.createXmlMapper(false).build();
        simpleModule.addDeserializer(PageResult.class, new PageResultDeserializer(mapper, paginationProperties));
        objectMapper.registerModule(simpleModule);
    }

}
